package mya.mes.mdc.module.rest;


import mya.common.jaxrs.op.OpDelete;
import mya.mes.mdc.db.DbHelper;
import mya.mes.mdc.logic.tag.PlcTagCache;
import mya.mes.mdc.model.excel.ExcelFileData;
import mya.mes.mdc.model.system.TagType;
import mya.mes.mdc.module.service.ExcelImportService;
import mya.mes.mdc.module.service.impl.ExcelImportServiceImpl;
import mya.mes.mdc.share.vo.MdcOptions;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.criteria.CriteriaDelete;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.util.List;

/**
 * tag excel 文件操作
 *
 * @author zll
 */
@Path("/mdc/excel")
public class TagExcelResource {

    /**
     * 解析 tag excel
     *
     * @param file
     * @return
     */
    @GET
    public String importExcel(@QueryParam("file") String file) {
        if (file != null && StringUtils.isNotBlank(file)) {
            System.out.println("Tag excel file uploaded.Begin parse..." + file);
            ExcelImportService service = new ExcelImportServiceImpl();
            ExcelFileData excel = new ExcelFileData();
            excel.line = file;
            excel.excelFile = MdcOptions.EXCEL_ROOT_FOLDER + file + ".xlsx";

            try {
                DbHelper.run(context -> {
                    List<TagType> list = context.em.createNativeQuery("select * from tag_type where line_name=" + "'" + excel.line + "'", TagType.class).getResultList();
                    if (list != null && list.size() > 0) {
                        for (TagType tagType : list) {
                            context.em.remove(tagType);
                        }
                    }
                    return null;
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

            List<TagType> excelData = service.tagDefExcel(excel);
            if (excelData != null && excelData.size() > 0) {
                for (TagType tagType : excelData) {
                    try {
                        DbHelper.run(context -> {
                            context.em.persist(tagType);
                            return null;
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            try {
                PlcTagCache.getInstance().initTagType();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "ok";
        }
        return "no";
    }

}